/*
 * Copyright (c) 2015. For Intelligent Group.
 */


package com.intelligent.ispc.mail;


import com.intelligent.ispc.cache.EmailCacheFactory;
import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.common.utils.ExceptionMessages;
import com.intelligent.ispc.foundation.mail.MailConfiguration;
import com.intelligent.ispc.foundation.mail.EmailStatus;
import com.intelligent.ispc.foundation.mail.MailDto;
import com.intelligent.ispc.foundation.mail.MailSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;


/**
 * Created by Julia.Zhou on 2015/12/7.
 */
@Service
public class MimeMailServiceImpl
{
    private static Logger LOGGER = LoggerFactory.getLogger(MimeMailServiceImpl.class);

    @Autowired
    private EmailCacheFactory emailCacheFactory;

    @Autowired
    private MailSender javaMailSender;

    /**
     * Send notification messages in MIME format.
     */
    public void sendMail(final MailDto targetDTO)
    {
        try {
            if (targetDTO == null) {
                throw new ApplicationException(ExceptionMessages.EXCEPTION_PARAMETER_INPUT_INVALID);
            }

            MailConfiguration emailDto = emailCacheFactory.getCacheEmail().get(EmailStatus.ACTIVE);
            javaMailSender.sendMailAsynchronously(targetDTO, emailDto);
        } catch (Exception e) {
            LOGGER.error("Send mail failed!", e);
        }
    }

    /**
     * Asynchronous sending MIME format the user to modify the notification message.
     */
    public void sendMailAsynchronously(final List<MailDto> mailDTOs)
    {
        for (MailDto target : mailDTOs) {
            sendMail(target);
        }
    }

    /**
     * Asynchronous sending MIME format the user to modify the notification message.
     */
    public void sendMailAsynchronously(final MailDto mailDTO)
    {
        sendMail(mailDTO);
    }

    public void testEmail(final MailConfiguration emailDto)
    {
        try {
            if (emailDto == null) {
                throw new ApplicationException(ExceptionMessages.EXCEPTION_PARAMETER_INPUT_INVALID);
            }

            MailDto targetDTO = new MailDto();
            targetDTO.setSubject("Test Email");
            targetDTO.setContent("Test Email");
            targetDTO.setTargetAddress(emailDto.getSendAddress());
            targetDTO.setNickname("All");
            javaMailSender.testEmail(targetDTO, emailDto);
            LOGGER.info("Send mail success!");
        }
        catch (Exception e) {
            LOGGER.error("Send mail failed!", e);
            throw new ApplicationException(e);
        }
    }

    public void invalidateAllEmailCache() {
        emailCacheFactory.getCacheEmail().invalidateAll();
    }

}
